package com.zhieasy.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import com.zhieasy.common.annotation.AccessLimit;
import com.zhieasy.common.api.CommonResult;
import com.zhieasy.common.exception.Asserts;
import com.zhieasy.common.util.FilesUtil;
import com.zhieasy.common.util.JwtUtil;
import com.zhieasy.domain.Student;
import com.zhieasy.domain.StudentInfoVo;
import com.zhieasy.service.StudentRedisService;
import com.zhieasy.service.StudentService;
import com.zhieasy.xpuapi.core.XpuApi;
import com.zhieasy.xpuapi.entity.StudentPojo;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author 风亦未止
 * @date 2021/11/3 15:57
 */
@Slf4j
@Api(tags = "学生操作相关接口")
@RestController
@RequestMapping("stu")
public class UserController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private XpuApi xpuApi;
    @Autowired
    private StudentRedisService studentRedisService;
    @Resource
    private FilesUtil fileDfsUtil;
//    @Resource
//    private HttpServletResponse response;

    @ApiOperation(value = "获取教务系统验证码")
    @GetMapping("/checkCode")
    public String getCheckCode(@RequestParam("stuId") @ApiParam(value = "学号") String stuId){
        return xpuApi.getCheckCodeUrl(stuId);
    }

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public CommonResult login(@RequestParam("stuId") @ApiParam(value = "学号") String stuId,
                              @RequestParam("password") @ApiParam(value = "密码") String password,
                              @RequestParam("checkCode") @ApiParam(value = "验证码") String checkCode){
        StudentPojo studentPojo = null;
        try {
            studentPojo = xpuApi.go(stuId, password, checkCode);
            if (ObjectUtil.isNull(studentPojo)){
                return CommonResult.failed("登录失败，请填写正确信息！");
            }
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        //UserService service = new UserServiceImpl();
        //service.SaveUser(go);
        Student student = studentService.getById(studentPojo.getStudentId());
        if (ObjectUtil.isNull(student)){
            //未登录过，则保存信息。
            student = new Student();
            student.setStudentId(studentPojo.getStudentId());
            student.setStudentName(studentPojo.getStudentName());
            student.setCollege(studentPojo.getCollege());
            student.setGrade(studentPojo.getGrade());
            student.setMajor(studentPojo.getMajor());
            studentService.save(student);
        }
        //获取token
        String token = JwtUtil.getToken(student);
        //保存至redis
        studentRedisService.put(token,student);
        return CommonResult.success(token,"登录成功！");
    }

    @ApiOperation(value = "获取信息")
    @GetMapping("/info")
    @AccessLimit(seconds = 1,maxCount = 5)
    public CommonResult info(@RequestHeader("token") String token){
        Student redisStudent = (Student) studentRedisService.get(token);
        StudentInfoVo student = studentService.getInfo(redisStudent);

        //在线预览api
        String onlineAPI="https://file.zhiyitimetable.cn/onlinePreview?url=";
        //简历真实地址
        String fileUrl="https://files.zhiyitimetable.cn/"+student.getFilePath();
        String encode="";
        try {
            encode=URLEncoder.encode(Base64.encode(fileUrl), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        student.setFilePath(StringUtil.isNullOrEmpty(student.getFilePath())?"0":(onlineAPI+encode));
        return CommonResult.success(student);
    }

    @ApiOperation(value = "学习方向选择")
    @PostMapping("/setDirection")
    @AccessLimit(seconds = 1,maxCount = 5)
    public CommonResult setDirection(@RequestHeader("token") String token,
                                     @RequestParam("directionId") Integer id ){
        if (id<0){
            return CommonResult.failed("选择失败！");
        }
        Student redisStudent = (Student) studentRedisService.get(token);
        Student student = studentService.getById(redisStudent.getStudentId());
        Integer newId=0;
        switch (id){
            case 1:
                newId=-1;
                break;
            case 2:
                newId=-2;
                break;
            case 3:
                newId=-3;
                break;
            case 4:
                newId=-4;
                break;
            case 5:
                newId=-5;
                break;
            case 6:
                newId=-6;
                break;
            case 7:
                newId=-7;
                break;
            case 8:
                newId=-8;
                break;
            default:
                newId=0;
        }
        student.setDirectionId(newId);
        boolean b = studentService.updateById(student);
        if (b){
            return CommonResult.success(null,"选择成功！");
        }
        return CommonResult.failed("选择失败！");
    }

    @ApiOperation(value = "退出登录！")
    @PostMapping("/loginOut")
    public void loginOut(@RequestHeader("token") String token){
        boolean remove = studentRedisService.remove(token);
        if (remove){
            log.info("已清除缓存！");
        }else {
            log.info("清除失败！");
        }
    }

    @ApiOperation(value = "简历上传")
    @PostMapping("/upload")
    @AccessLimit(seconds = 2,maxCount = 3)
    public CommonResult upload(@RequestHeader("token") String token,
            @RequestParam("file") @ApiParam(value = "文件") MultipartFile file){
        Student redisStudentInfo = (Student) studentRedisService.get(token);
        Student student = studentService.getById(redisStudentInfo.getStudentId());
        //有路径就删除，做覆盖
        if(!StringUtil.isNullOrEmpty(student.getFilePath())){
            //删除失败不会执行下一步。
            fileDfsUtil.deleteFile(student.getFilePath());
        }
        if (student.getIsSubmit()==0){
            student.setIsSubmit(1);
        }
        String result="";
        try {
            String path = fileDfsUtil.upload(file);
            if (!StringUtils.isEmpty(path)) {
                result=path;
            } else {
                Asserts.fail("上传失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Asserts.fail("服务异常！");
        }
        student.setFilePath(result);
        studentService.updateById(student);
        return CommonResult.success(null,"上传成功！");
    }

    @ApiOperation(value = "提交")
    @PostMapping("/submit")
    @AccessLimit(seconds = 2,maxCount = 3)
    public CommonResult submit(@RequestHeader("token") String token,
                               @RequestParam("sex") @ApiParam(value = "性别") String sex,
                               @RequestParam("phone") @ApiParam(value = "手机号码") String phone,
                               @RequestParam("email") @ApiParam(value = "邮箱") String email,
                               @RequestParam("weChat") @ApiParam(value = "微信号码") String weChat,
                               @RequestParam("qq") @ApiParam(value = "qq号") String qq){
        Student redisStudentInfo = (Student) studentRedisService.get(token);
        Student student = studentService.getById(redisStudentInfo.getStudentId());
        student.setSex(sex);
        student.setPhone(phone.trim());
        student.setEmail(email.trim());
        student.setWeChat(weChat.trim());
        student.setQq(qq.trim());
        boolean b = studentService.updateById(student);
        if (b){
            return CommonResult.success(null,"提交成功！");
        }
        return CommonResult.failed("提交失败！");
    }

//    @ApiOperation(value = "文件删除")
//    @PostMapping("/delete")
//    @AccessLimit(seconds = 2,maxCount = 3)
    public CommonResult delete(@RequestHeader("token") String token){
        Student redisStudentInfo = (Student) studentRedisService.get(token);
        Student student = studentService.getById(redisStudentInfo);
        //删除失败不会执行下一步。
        fileDfsUtil.deleteFile(student.getFilePath());
        //更新数据库
        student.setFilePath("");
        studentService.updateById(student);
        // String filePathName = "group1/M00/00/00/wKhjZF3WEDmAPSglAABSZAhj0eU111.jpg" ;
        return CommonResult.success(null,"删除成功！");
    }

//    @ApiOperation(value = "简历下载")
//    @PostMapping("/download")
//    @AccessLimit(seconds = 2,maxCount = 3)
    public void download(@RequestHeader("token") String token,HttpServletResponse response) throws IOException {
        Student redisStudentInfo = (Student) studentRedisService.get(token);
        Student student = studentService.getById(redisStudentInfo.getStudentId());
        String name=student.getStudentName();
        String filePath=student.getFilePath();
        //下载的文件名
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name,"utf-8"));
        //下载对应的文件
        byte[] bytes = fileDfsUtil.downloadFile(filePath);
        response.getOutputStream().write(bytes);
        // 刷新缓存
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    @ApiOperation(value = "更新信息")
    @PostMapping("/update")
    @AccessLimit(seconds = 2,maxCount = 3)
    public CommonResult update(@RequestHeader("token") String token,
                               @RequestParam("sex") @ApiParam(value = "性别") String sex,
                               @RequestParam("phone") @ApiParam(value = "手机号码") String phone,
                               @RequestParam("email") @ApiParam(value = "邮箱") String email,
                               @RequestParam("weChat") @ApiParam(value = "微信号码") String weChat,
                               @RequestParam("qq") @ApiParam(value = "qq号") String qq){
        Student redisStudentInfo = (Student) studentRedisService.get(token);
        Student student = studentService.getById(redisStudentInfo.getStudentId());
        student.setSex(sex);
        student.setPhone(phone.trim());
        student.setEmail(email.trim());
        student.setWeChat(weChat.trim());
        student.setQq(qq.trim());
        boolean b = studentService.updateById(student);
        if (b){
            return CommonResult.success(null,"修改成功！");
        }
        return CommonResult.failed("修改失败！");
    }

//    @ApiOperation(value = "简历下载")
//    @PostMapping("/newDownload")
//    public void newDownload(@RequestHeader("token") String token,HttpServletResponse response) throws IOException {
//        Student redisStudentInfo = (Student) studentRedisService.get(token);
//        Student student = studentService.getById(redisStudentInfo.getStudentId());
//        String name=student.getStudentName();
//        String filePath=student.getFilePath();
//        String url="192.168.204.128/"+filePath;
//        //下载的文件名
//        response.setContentType("application/octet-stream");
//        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name,"utf-8"));
//        response.sendRedirect(url);
//    }
}
